<template>
	<u-popup :show="show" mode="center" @close="close" :closeOnClickOverlay="false">
		<view class="mask">
			<view class="is_update" v-if="!is_update">
				<view class="content">发现新版本，是否更新?</view>
				<view class="btns">
					<u-button class="btn" text="暂不更新" @tap="close"></u-button>
					<u-button class="btn confirm" text="立即更新" @tap="confirm"></u-button>
				</view>
			</view>
			<view class="progress_box" v-if="is_update">
				<text>努力更新中...</text>
				<progress :percent="downloadProgress" color="#2e5c1e" show-info />
			</view>
		</view>
	</u-popup>
</template>

<script>
	export default {
		name: "updataView",
		data() {
			return {
				show: false,
				is_update: false,
				downloadProgress: 0,
				downloadTask: null
			};
		},
		methods: {
			openMask() {
				if (uni.getStorageSync("update") && uni.getStorageSync("update") == true) {
					this.show = true
				} else {
					return
				}
				uni.removeStorageSync("update")
				uni.hideTabBar()
				this.$emit("maskShow", true)
			},
			close() {
				this.show = false
				this.$emit("maskShow", false)
				setTimeout(() => {
					uni.showTabBar()
				}, 300)
			},
			confirm() {
				let that = this
				that.is_update = true
				const downloadUrl = uni.getStorageSync("wgtUrl");
				that.downloadTask = uni.downloadFile({
					url: downloadUrl,
					success: (res) => {
						// 下载成功
						if (res.statusCode === 200) {
							plus.runtime.install(
								res.tempFilePath, {
									force: true
								}, () => {
									that.percent = 100
									plus.nativeUI.toast("更新成功,正在重启稍等")
									uni.removeStorageSync("wgtUrl")
									that.close()
									setTimeout(() => {
										plus.runtime.restart();
									}, 300);
								},
								function(e) {
									plus.nativeUI.toast("安装失败")
									setTimeout(() => {
										uni.removeStorageSync("wgtUrl")
										that.close()
									}, 300);
								}
							)
						} else {
							uni.showToast({
								title: '下载失败',
								icon: 'none',
							});
							that.is_update = false
						}

					},
				});
				// 监听下载进度
				this.downloadTask.onProgressUpdate((res) => {
					console.log(res, "@@@@@@@@@@下载相关")
					this.downloadProgress = res.progress;
				});
			}
		},
		watch: {
			// downloadProgress(newVal, oldVal) {
			// 	if (newVal == 100) {
			// 		this.close()
			// 	}
			// }
		}
	}
</script>

<style lang="less" scoped>
	/deep/.u-popup__content {
		background: transparent;
	}

	.mask {
		width: 80vw;
		border-radius: 40rpx;
		background: #fff;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.6);
		padding-top: 30rpx;
		overflow: hidden;

		.is_update {
			.content {
				padding: 0 30rpx;
			}

			.btns {
				display: flex;
				align-items: center;
				margin-top: 20rpx;
				border-top: 2rpx solid rgba(0, 0, 0, 0.1);

				.btn {
					flex: 1;
					border: none;
					font-size: 28rpx;
				}

				.confirm {
					color: #2e5c1e;
				}
			}
		}

		.progress_box {
			padding: 0 30rpx 30rpx;
		}
	}
</style>